<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>购物车</span>
      </div>
    </template>

    <!-- 购物车为空状态 -->
    <el-empty description="购物车为空" v-if="cartList.length === 0"/>

    <!-- 购物车列表 -->
    <el-table :data="cartList" style="width: 100%" v-else>
      <el-table-column label="商品图片" prop="picture">
        <template #default="{row}">
          <el-image
              :src="row.picture ? `/api/file/download.do?filename=${encodeURIComponent(row.picture)}` : '/default2.png'"
              hide-on-click-modal
              fit="cover"
              style="width: 80px; height: 80px"
          />
        </template>
      </el-table-column>
      <el-table-column label="商品名称" prop="name"></el-table-column>
      <el-table-column label="单价" prop="price"></el-table-column>
      <el-table-column label="数量" prop="quantity">
        <template #default="{row}">
          <el-input-number v-model="row.quantity" :min="1" @change="handleQuantityChange(row)"/>
        </template>
      </el-table-column>
      <el-table-column label="小计">
        <template #default="{row}">
          ¥{{ (row.price * row.quantity).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{row}">
          <el-button type="text" @click="removeFromCart(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 结算区域 -->
    <div class="checkout-bar" v-if="cartList.length > 0">
      <div class="total">
        <span>总计: ¥{{ totalAmount }}</span>
      </div>
      <el-button type="primary" @click="checkout">结算</el-button>
    </div>
  </el-card>
</template>

<script setup>
import { computed } from 'vue';
import { useCartStore } from '@/stores/cartStore';
import { ElMessage } from 'element-plus';

// 初始化购物车store
const cartStore = useCartStore();

// 从store获取购物车列表
const cartList = computed(() => cartStore.items);

// 从store获取总金额
const totalAmount = computed(() => cartStore.totalAmount);

// 数量变更处理
const handleQuantityChange = (row) => {
  cartStore.updateQuantity(row.id, row.quantity);
  ElMessage.success('数量已更新');
};

// 从购物车移除商品
const removeFromCart = (id) => {
  cartStore.removeItem(id);
};

// 结算处理
const checkout = () => {
  if (cartList.value.length === 0) {
    ElMessage.warning('购物车为空，无法结算');
    return;
  }
  // 显示结算成功消息
  ElMessage.success(`结算成功，支付总金额：${cartStore.totalAmount}元`);
  // 清空购物车
  cartStore.clearCart();
};
</script>

<style scoped>
.page-container {
  margin: 20px;
}

.header {
  font-size: 18px;
  font-weight: bold;
}

.checkout-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 10px;
  border-top: 1px solid #eee;
}

.total {
  font-size: 16px;
  font-weight: bold;
  color: #ff4d4f;
}
</style>